package top.hekun.study.core.util;

import top.hekun.study.core.model.ByteBufferProxy;

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * 〈class文件工具〉
 *
 * @author: Sakura
 * @date: 2023/4/24
 */
public class ClassFileUtil {

    /**
     * 根据文件名称获取class代码
     * @param className
     * @return
     */
    public static  byte[] getClassFileByteToClassName(String className){
        File filePath = new File(new File(System.getProperty("user.dir"), "asm"), "out");
        File file = new File(new File(new File(new File(new File(new File(new File(new File(filePath,
                "production"), "classes"), "top"), "hekun"), "study"), "core"), "model"), className + ".class");
        long length = file.length();
        byte[] bytes = new byte[Math.toIntExact(length)];
        //文件内容输入 读取
        try (FileInputStream inputStream = new FileInputStream(file);) {
            inputStream.read(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    /**
     * 获取第三部分代码路径
     * @return
     */
    public static File getThreePath(){
        File filePath= new File(new File(System.getProperty("user.dir"),"asm"),"src");
        File file = new File(new File(new File(new File(new File(new File(filePath,
                "main"),"java"),"top"),"hekun"),"study"),"three");
        return file;
    }
    public static File getFourPath(){
        File filePath= new File(new File(System.getProperty("user.dir"),"asm"),"src");
        File file = new File(new File(new File(new File(new File(new File(filePath,
                "main"),"java"),"top"),"hekun"),"study"),"four");
        return file;
    }

    public static void  classFileCoreWrite(byte[] core,File  classFilePath){
        try (
                //文件内容覆盖模式--推荐
                FileOutputStream outputStream = new FileOutputStream(classFilePath, false);
                // 获取通道
                FileChannel channel = outputStream.getChannel()
        ) {
            ByteBufferProxy byteBufferProxy = ByteBufferUtil.getByteBufferProxyByWrap(core);
            byteBufferProxy
                    .compact()
                    .writeChannel(channel);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File getClassFileModelPath() {
        File filePath= new File(new File(System.getProperty("user.dir"),"asm"),"src");
        File file = new File(new File(new File(new File(new File(new File(filePath,
                "main"),"java"),"top"),"hekun"),"study"),"classFileModel");
        file.mkdirs();
        return file;
    }
}
